<template lang="pug">
  <div>
    el-dialog(
      :visible.sync="show"
      top="5vh"
      width="560px"
      @open="beforeOpen"
      :before-close="handleClose"
      :close-on-click-modal="false"
      custom-class="dialog-border"
    )
      .modal-title(slot="title") {{ title }}
      el-form(
        :model="form"
        size="small"
        :rules="rules"
        ref="memberForm"
        label-width="100px"
        )
        el-form-item(label="品牌名称：" :label-width="formLabelWidth" prop="name" )
          el-input(v-model="form.name" autocomplete="off" ) 
        el-form-item(label="商标注册号：" :label-width="formLabelWidth" prop="trademarkRegistrationNumber" )
          el-input(v-model="form.trademarkRegistrationNumber" autocomplete="off")
        el-form-item(label="品牌公司：" :label-width="formLabelWidth" prop="brandCompany" )
          el-input(v-model="form.brandCompany" autocomplete="off")   
        el-form-item(label="产地：" :label-width="formLabelWidth" prop="isImport" )
          el-select(v-model="form.isImport" placeholder="请选择产地" style="width:100%" autocomplete="off") 
            el-option(label="进口" :value="1")
            el-option(label="国产" :value="2") 
        el-form-item(label="代理公司：" :label-width="formLabelWidth" prop="companyList" v-if="agencyShow")
          .el-agency
            p(v-for="item in form.companyList" disabled) {{item.companyName}} 
        

        el-form-item(label="品牌logo：" required :label-width="formLabelWidth")
          .el-form-info 仅允许上传一张图片，文件大小≤5MB
          .el-form-bd
            el-upload(
              action="#"
              class="upload-demo"
              :limit="limit"
              :multiple="false"
              accept="image/png, image/jpeg, image/jpg"
              ref="hiddenUpload"
              :file-list="imgList"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleLogoChange"
              list-type="picture-card"
              :on-remove="handleRemove"
              :on-exceed="handleGridExceed"
            )
              .el-upload-btn(slot="trigger")
                .iconfont.icon-tianjia
                .el-upload-btn-txt 点击上传
            .el-form-file(v-if="logoFiles.length" @mouseover="mouseOverPreview" @mouseleave="mouseLeavePreview" )
              .el-form-img(v-for="item, index in logoFiles", :style="{'background-image':`url(${item.url})`}")
                .el-bgcover(v-show="showBgCover") 
                  .iconfont.icon-chakan(@click="urlPicturePreview(item)")
                  .iconfont.icon-shanchu1(@click="delFiles('logoFiles', index)")                                 
            .el-form-file(v-if="form.logoUrl" @mouseover="mouseOverPreview" @mouseleave="mouseLeavePreview")
              .el-form-img(:style="{'background-image':`url(${form.logoUrl})`}")
                .el-bgcover(v-show="showBgCover")
                  .iconfont.icon-chakan(@click="logoUrlPicturePreview")                 
                  .iconfont.icon-shanchu1(@click="delLogoUrl")           
      div(slot="footer" class="dialog-footer")
        el-button(@click="handleClose") 取消
        el-button(type="primary" @click="save") 确 定
    el-dialog(:visible.sync="dialogPreviewVisible" width="638px" )
      div.preview
        img(width="638px" height="638px;margin-top:-30px" :src="dialogImageUrl" alt="" )    
  </div>
</template>

<script>
import { getBrandInformation,addOrUpdateBrand,FileUpload } from 'api'
export default {
  name: 'addBrandModel',
  props:{
    show: Boolean,
    item: Object
  },
  data() {
    return {
      imgList:[],
      dialogVisible: false,
      dialogPreviewVisible:false,
      dialogFormVisible: false,
      title:'品牌添加',
      logoFiles: [],
      showBgCover:false,
      agencyShow:'',
      form: {
        name: '',
        trademarkRegistrationNumber: '',
        brandCompany:'',
        isImport: '',
        companyList: [],
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' }
        ],
        trademarkRegistrationNumber: [
          { required: true, message: '请输入商标注册号', trigger: 'blur' },
        ],
        brandCompany: [
          { required: true, message: '请输入品牌公司', trigger: 'blur' }
        ],
        isImport: [
          { required: true, message: '请选择产地', trigger: 'change' }
        ]
      },
      formLabelWidth: '108px',
      dialogImageUrl:'',
      dialogVisible: false,
      restaurants:[]
    }
  },
  computed: {
    limit () {
      let len = 0
      if (this.form.logoUrl) {
        len = 2
      }
      return 1 - len
    }
  },
  methods:{
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    mouseOverPreview(){
      this.showBgCover = true     
    },
    mouseLeavePreview(){
      this.showBgCover = false
    },
    urlPicturePreview(file){
      this.dialogImageUrl = file.url;
      this.dialogPreviewVisible = true;
    },
    logoUrlPicturePreview() {
      this.dialogImageUrl = this.form.logoUrl;
      this.dialogPreviewVisible = true;
    },
    handleClose () {
      this.$emit('close')
      this.$refs.hiddenUpload.clearFiles()
    },
    async handleLogoChange (file, fileList) {
      const valid = await this.filterFileSize(file.size)
      if (!valid) {
        let index = fileList.findIndex(item => item.uid === file.uid)
        fileList.splice(index,1)
        this.$message.error('图片大小≤5MB！')
        return
      }
      this.$refs.hiddenUpload.clearFiles()
      this.form.logo = ''
      this.form.logoUrl = ''
      this.logoFiles = fileList
    },
    handleGridExceed () {
      this.$message.error('最多只能上传1张图片！')
    },
    async fileUpload (raw) {
      // if (this.logoFiles.length + this.form.logoUrl.length > 1) {
      //   this.$message.error('最多上传一张ha！')
      //   return
      // }
      return new Promise(async (resolve, reject) => {
        try {
          let formData = new FormData()
          formData.append('Filedata', raw)
          formData.append("applicationId", 4)
          const { ResultSet } = await this.$axios.post(FileUpload, { formData: formData, isUpload: true }, { headers:{ "Content-Type": "multipart/form-data" } })
          resolve({ ...ResultSet.Result[0] })
        } catch (err) {
          console.log(err)
          reject(err)
        }
      })
    },
    async submit () {
      if (!this.logoFiles.length && !this.form.logoUrl) {
        this.$message.error('请上传品牌logo！')
        return
      }
      if (this.logoFiles.length) {
        const logoFile = await this.fileUpload(this.logoFiles[0].raw)
        this.form.logo = logoFile.fileId
        this.form.logoUrl = logoFile.fileUrl
      }
      try {
        let query = { ...this.form }
        // console.log(this.form)
        await this.$axios.post(addOrUpdateBrand,  { ...query } )
        this.$message.success('保存成功！')
        this.$emit('confirm')
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    save () {
      this.$refs.memberForm.validate((valid) => {
        console.log(valid)
        if (valid) this.submit()
      })
    },
    async beforeOpen () {
      this.logoFiles = []
      if (this.item.id) {  
        // console.log(this.item.logoUrl)
        const { ResultSet } = await this.$axios.post(getBrandInformation, { brandId:this.item.id })    
        this.form = { ...ResultSet.userData.brandInformation }
        this.title= "品牌编辑"
        this.agencyShow = true
      } else {
        this.form = {
          name: '',
          isImport: '',
          brandCompany: '',
          trademarkRegistrationNumber: '',
          logoUrl: '',
          id: ''
        },
        this.title= "添加品牌"
        this.agencyShow = false
      }
    },
    async initRestaurants () {
      try {
        const { ResultSet } = await this.$axios.post(getBrandInformation, this.form.name)
        this.restaurants = ResultSet.Result
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    filterFileSize (size) {
      return new Promise((resolve, reject) => {
        const defaultSize = 5 //MB
        if (size <= 5 * 1024 * 1024) {
          resolve(true)
        } else {
          resolve(false)
        }
      })
    },
    
    delFiles (key, index) {
      this[key].splice(index, 1)
    },
    delLogoUrl () {
      this.form.logo = ''
      this.form.logoUrl = ''
    },
  },
  
  // beforeRouteEnter (to, from, next) {
  //   // ...
  //   next(vm => {
  //     vm.initRestaurants()
  //     if (to.params.id) {
  //       vm.title = '品牌编辑'  
  //       vm.getBrandLibraryList()            
  //     } else {
  //       vm.title = '品牌添加'
  //     }
  //   })
  // },
}
</script>
<style type="text/css" lang="scss">
.upload-demo {
  .el-upload--picture-card {
    width: 98px;
    height: 98px;
    line-height: 1;
  }
  .el-upload-btn-txt {
    margin-top: 15px;
  }
}

</style>
<style lang="scss" scoped>
  .modal-title{
    font-size:16px;
    font-weight:bold;
  }
  .el-dialog__header{
    border-bottom:1px solid #ccc;
  }
  .el-form-bd {
    margin-top: 15px;
    display: flex;
    // margin-left:100px;
  }
  .el-form-info {
    font-size: 14px;
    color: #AFAFAF;
  }
  .el-form-file {
    display: flex;
    align-items: center;
    .el-form-img {
      position: relative;
      width: 96px;
      height: 96px;
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;
      margin-left: 16px;
      border-radius: 4px;
    .icon-chakan {
      position: absolute;
      top: 50%;
      right: 21%;
      transform: translate(50%, -50%);
      cursor: pointer;
      color: #fff;
    }
    .icon-shanchu1{
      position: absolute;
      top: 50%;
      left: 21%;
      transform: translate(50%, -50%);
      cursor: pointer;
      color: #fff;
    }
  }
  .el-bgcover{
    position:absolute;
    top:0;
    left:0;
    width:96px;
    height:96px;
    background-color:#333;
    opacity: 0.7;
    border-radius:4px;
    z-index:1000;
    cursor: pointer;
  }
}
.el-agency{
  border:1px solid #DCDFE6;
  padding:8px 15px;
  border-radius: 4px;
  min-height:32px;
  p{
    line-height:23px;
  }
}
.el-upload--picture-card i{
  font-size:14px;
}
.el-upload-btn {
  width: 96px;
  height: 96px;
  background: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  color: #B2B4C7;
  .iconfont {
    font-size: 20px;
    font-weight: bold;
  }
  .el-upload-btn-txt {
    font-size: 14px;
  }
}
.el-upload--picture-card{
  line-height:32px;
}
.el-upload{
  width:96px;
  height:96px;
}
.preview{
  width:638px;
  height:100%;
  display:flex;
  align-items:center;
  justify-content: center;
}
.preview img{
  width: 638px;
  height: 638px !important;
  margin-top: -60px;
  margin-bottom: -30px;
  margin-left: -70px;
  margin-right: -30px;
}
.el-dialog__body{
  padding:0!important;
}
</style>